package com.keyin.widget;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.keyin.CatalogActivity;
import com.keyin.R;
import com.keyin.ReadMagazineActivity;
import com.keyin.protocol.CacheImageProtocol;
import com.keyin.protocol.DownloadMagazine;
import com.keyin.protocol.MagazineBean;
import com.keyin.protocol.MagazineIndexCache;
import com.keyin.protocol.Periodical;

public class BookShelfWidget extends MainWidgetBase {

	private View container;
	private List<Periodical> peridocals;
	
	private BaseAdapter adapter;

	public BookShelfWidget(Activity context) {
		super(context);
	}

	@Override
	public void onNewIntent(Intent i) {
		if (container == null) {
			container = View.inflate(getContext(), R.layout.v_book_shelf, null);
			addView(container);
		}

		peridocals = MagazineIndexCache.list();
		refreshUI();
	}

	private void refreshUI() {
		ListView listView = (ListView) findViewById(R.id.magazine_list);
		adapter = new BaseAdapter() {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View view = null;
				if (view == null) {
					view = View.inflate(getContext(), R.layout.v_list_item,
							null);
				}

				Periodical bean = peridocals.get(position);

				ImageView img = (ImageView) view.findViewById(R.id.cover);
				String imgUrl = bean.cover_img;
				if (imgUrl != null) {
					CacheImageProtocol imgProtocol = new CacheImageProtocol(
							getContext(), imgUrl);
					imgProtocol.startTrans(img);
				}

				TextView name = (TextView) view.findViewById(R.id.name);
				name.setText(bean.name);

				TextView date = (TextView) view.findViewById(R.id.date);
				date.setText(bean.number);

				TextView intro = (TextView) view.findViewById(R.id.intro);
				intro.setText(bean.description);
				return view;
			}

			@Override
			public long getItemId(int position) {
				return 0;
			}

			@Override
			public Object getItem(int position) {
				return null;
			}

			@Override
			public int getCount() {
				return peridocals.size();
			}
		};
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent i = new Intent(BookShelfWidget.this.parent, CatalogActivity.class);
				i.putExtra("peridocal_id", peridocals.get(position).periodical_id);
				BookShelfWidget.this.parent.startActivity(i);
			}
		});
	}
}
